<template>
    <div class="wh-100% flex flex-col gap-10px ove">
        <SearchCard :model="'staff'" />
        <n-card class="h-full" title="员工列表">
            <template #header-extra>
                <div class="flex gap-10px">
                    <n-button
                        ghost
                        size="small"
                        :focusable="false"
                        @click="handleRefreshPage"
                    >
                        <template #icon>
                            <n-icon :component="RefreshCircle" />
                        </template>
                        刷新
                    </n-button>
                    <n-button
                        ghost
                        type="info"
                        size="small"
                        :focusable="false"
                        @click="
                            staffFormvisible = true;
                            staffFormModel = 'create';
                            currentStaff = null;
                        "
                    >
                        <template #icon>
                            <n-icon :component="Add" />
                        </template>
                        新增
                    </n-button>
                    <n-button
                        ghost
                        type="error"
                        size="small"
                        :disabled="selectedStaffs.length === 0"
                        :focusable="false"
                        @click="handleDeleteStaff('batch')"
                    >
                        <template #icon>
                            <n-icon :component="Trash" />
                        </template>
                        批量删除
                    </n-button>
                </div>
            </template>
            <n-data-table
                :loading="loading"
                :columns="columns"
                :data="currentStaffs"
                :row-key="(row: User) => row.id"
                @update:checked-row-keys="
                    (keys: DataTableColumnKey[]) => {
                        selectedStaffs = currentStaffs.filter(
                            (staff) => keys.includes(staff.id!)
                        );
                    }
                "
            >
            </n-data-table>
            <template #footer>
                <div class="w-full flex justify-end">
                    <n-pagination
                        v-model:page="pagination.page"
                        :page-count="
                            Math.ceil(pagination.total / pagination.pageSize)
                        "
                        @update:page="handleChangePage"
                    >
                        <template #prefix>
                            <span>共 {{ pagination.total }} 条</span>
                        </template>
                    </n-pagination>
                </div>
            </template>
        </n-card>
        <n-drawer
            v-model:show="staffFormvisible"
            :width="360"
            placement="right"
        >
            <n-drawer-content>
                <template #header>
                    {{
                        staffFormModel === "create"
                            ? "新增员工"
                            : "编辑员工信息"
                    }}
                </template>
                <UserForm
                    :role="'staff'"
                    :model="staffFormModel"
                    :data="currentStaff"
                    @submit:data="
                        (data) =>
                            staffFormModel === 'create'
                                ? handleAddStaff(data)
                                : handleUpdateStaff(data)
                    "
                    @update:password="handleUpdateStaff"
                />
            </n-drawer-content>
        </n-drawer>
    </div>
</template>

<script lang="ts" setup>
import { h, ref, reactive, onMounted } from "vue";
import { RefreshCircle, Add, Trash } from "@vicons/ionicons5";

import type { User } from "@/service/api/types/user";
import { NTag, NButton, NDivider } from "naive-ui";
import type { DataTableColumns, DataTableColumnKey } from "naive-ui";

import { addUser, updateUser, deleteUser } from "@/service/api/modules/user";
import { getStaffCounts, getStaffsList } from "@/service/api/modules/staff";

import SearchCard from "../components/search-card/index.vue";
import UserForm from "@/components/user-form/index.vue";

const loading = ref(false);
// 表格列内容
const columns: DataTableColumns<User> = [
    {
        type: "selection",
    },
    {
        title: "账号",
        key: "account",
        align: "center",
    },
    {
        title: "昵称",
        key: "username",
        align: "center",
    },
    {
        title: "账号状态",
        key: "frozen",
        align: "center",
        render(row) {
            return h(NTag, { type: row.frozen ? "error" : "success" }, () => {
                return row.frozen ? "冻结" : "正常";
            });
        },
    },
    {
        title: "创建时间",
        key: "createdDate",
        align: "center",
        render(row) {
            return h("div", { class: "flex-center gap-10px" }, [
                new Date(row.createdDate).toLocaleDateString(),
            ]);
        },
    },
    {
        title: "操作",
        key: "action",
        align: "center",
        width: 200,
        render(row) {
            return h("div", { class: "flex-center gap-10px" }, [
                h(
                    NButton,
                    {
                        size: "small",
                        type: "primary",
                        ghost: true,
                        onClick: () => {
                            currentStaff.value = row;
                            staffFormvisible.value = true;
                            staffFormModel.value = "update";
                        },
                    },
                    () => {
                        return "编辑";
                    }
                ),
                h(NDivider, { vertical: true }),
                h(
                    NButton,
                    {
                        size: "small",
                        type: "error",
                        ghost: true,
                        onClick: () => {
                            currentStaff.value = row;
                            handleDeleteStaff("single");
                        },
                    },
                    () => {
                        return "删除";
                    }
                ),
            ]);
        },
    },
];
// 缓存的staff数据, key为页码, value为客户数据
const staffs: Map<number, User[]> = new Map();
// 当前页数据, 用于渲染表格
const currentStaffs = ref<User[]>([]);
// 选中的员工数据
const selectedStaffs = ref<User[]>([]);
// 当前要编辑的员工数据
const currentStaff = ref<User | null>(null);

const staffFormvisible = ref(false);
const staffFormModel = ref<"create" | "update">("update");

const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0,
});

const getStaffs = async () => {
    loading.value = true;
    try {
        const res = await getStaffsList({
            page: pagination.page,
            size: pagination.pageSize,
        });
        currentStaffs.value = res;
        staffs.set(pagination.page, res);
    } catch (err) {
        window.NMessage.error((err as Error).message);
    } finally {
        loading.value = false;
    }
};

onMounted(async () => {
    try {
        pagination.total = await getStaffCounts();
        if (pagination.total === 0) {
            return;
        }
        getStaffs();
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
});

// 切换分页
const handleChangePage = (page: number) => {
    pagination.page = page;
    if (staffs.has(page)) {
        currentStaffs.value = staffs.get(page) || [];
        return;
    }
    getStaffs();
};

const handleRefreshPage = async () => {
    pagination.page = 1;
    pagination.total = await getStaffCounts();
    currentStaffs.value = [];

    getStaffs();
};

const handleAddStaff = async (data: User) => {
    try {
        await addUser(data);
        staffFormvisible.value = false;
        pagination.total++;
        handleRefreshPage();
        window.NMessage.success("新增成功");
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
};

const handleUpdateStaff = async (data: User | string) => {
    try {
        if (typeof data === "string") {
            data = { ...currentStaff.value, password: data } as User;
        }
        await updateUser(data);
        staffFormvisible.value = false;
        handleRefreshPage();
        window.NMessage.success("更新成功");
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
};

const handleDeleteStaff = async (model: "single" | "batch") => {
    window.NDialog.warning({
        title: "警告",
        content: "确定要删除选中的员工?",
        closable: false,
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: async () => {
            try {
                if (model === "single") {
                    await deleteUser([currentStaff.value!.id!]);
                    pagination.total -= 1;
                } else {
                    let ids = selectedStaffs.value.map((staff) => staff.id!);
                    await deleteUser(ids);
                    pagination.total -= ids.length;
                }
                staffs.clear();
                handleRefreshPage();
                window.NMessage.success("删除成功");
            } catch (err) {
                window.NMessage.error((err as Error).message);
            }
        },
    });
};
</script>

<style scoped></style>
